package cn.ruituo.adv9;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;

public class ModifyXML {
    public static void main(String[] args) {
        //add(4,3,62.5F,"mysql数据库编程","邮电出版社","介绍了Sql语法的各个方面，><,!=,cancat");
        boolean f=delBook(3);
        System.out.println(f);
    }
    public static boolean delBook(int id){
        SAXReader reader = new SAXReader();
        //相对目录
        Document doc = null;
        try {
            doc = reader.read(new File("advance/src/cn/cn.ruituo/books.xml"));
        } catch (DocumentException e) {
            System.out.println("解析失败");
            e.printStackTrace();
            return false;
        }
        Element element=(Element)doc.selectSingleNode("/books/book[@id='"+id+"']");
        if(element==null)
            return false;

        element.getParent().remove(element);
        //保存
        //保存到xml中
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("utf-8");
        try {
            XMLWriter x=new XMLWriter(new FileOutputStream("advance/src/cn/cn.ruituo/books.xml"),format);
            x.write(doc);
            x.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
    //增加一本新书
    public static void add(int id,int diff,float price,String name,String publish,String desc){
        SAXReader reader = new SAXReader();
        //相对目录
        Document doc = null;
        try {
            doc = reader.read(new File("advance/src/cn/cn.ruituo/books.xml"));
        } catch (DocumentException e) {
            System.out.println("解析失败");
            e.printStackTrace();
            return;
        }
        Element root=doc.getRootElement();
        Element ebook=root.addElement("book");
        ebook.addAttribute("id",String.valueOf(id));
        ebook.addAttribute("diff",String.valueOf(diff));
        ebook.addElement("name").setText(name);
        ebook.addElement("publish").setText(publish);
        ebook.addElement("description").setText(desc);
        //保存到xml中
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("utf-8");
        try {
            XMLWriter x=new XMLWriter(new FileOutputStream("advance/src/cn/cn.ruituo/books.xml"),format);
            x.write(doc);
            x.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
